package com.example.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;

public class RedisServerNIO {

    static final ArrayList<SocketChannel> socketList = new ArrayList<>();
    static ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

    public static void main(String[] args) throws IOException {
        System.out.println("RedisServer 启动等待中...");
        try (ServerSocketChannel serverSocketChannel = ServerSocketChannel.open()) {
            serverSocketChannel.bind(new InetSocketAddress("localhost", 6379));
            serverSocketChannel.configureBlocking(false); // 设置为非阻塞模式

            while (true) {
                for (SocketChannel element :
                        socketList) {
                    int read = element.read(byteBuffer);
                    if (read > 0) {
                        System.out.println("接收到数据:" + read);
                        byteBuffer.flip();
                        byte[] bytes = new byte[read];
                        byteBuffer.get(bytes);
                        System.out.println("数据:" + new String(bytes));
                        byteBuffer.clear();
                    }
                }
//                // 删除已经关闭的连接
//                socketList.removeIf(s -> !s.isOpen());

                SocketChannel socketChannel = serverSocketChannel.accept();
                if (socketChannel != null) {
                    System.out.println("有新的连接");
                    socketChannel.configureBlocking(false);// 非阻塞
                    socketList.add(socketChannel);
                    System.out.println("当前连接数:" + socketList.size());

                }
            }
        }
    }
}
